package co.com.javeriana.aes.oms.orders.service;

import co.com.javeriana.aes.oms.common.entity.Items;
import co.com.javeriana.aes.oms.common.entity.Orders;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Jonathan Fernandez <jonathan.fvargas@gmail.com>
 */

@Local(OrdersServiceBeanLocal.class)
@Stateless(name = "OrdersServiceBean", mappedName = "ejb/OrdersServiceBean")
public class OrdersServiceBean implements OrdersServiceBeanLocal {

    @PersistenceContext(unitName = "OMS-PU")
    private EntityManager em;

    /**
     * 
     * @return 
     */
    @Override
    public List<Orders> getOrders() {

        List<Orders> orders = null;

        try {
            Query data = em.createNamedQuery("Orders.findAll");
            orders = data.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return orders;
    }    
    
    
    /**
     * 
     * @param id
     * @return
     * @throws javax.persistence.NoResultException 
     */    
    @Override
    public Orders getOrderById(Integer id) throws javax.persistence.NoResultException {

        Orders order = null;

        try {
            
            Query data = em.createNamedQuery("Orders.findByOrdid");
            data.setParameter("ordid", id);
            order = (Orders) data.getSingleResult();            
            order.getItemsList().size();
            
        } catch (javax.persistence.NoResultException e) {
            throw e;
        }
        return order;
    }
        
    
    /**
     * 
     * @param productID
     * @return
     * @throws javax.persistence.NoResultException 
     */    
    @Override
    public List <Orders> getOrderByProductID(Integer productID) throws javax.persistence.NoResultException {

        List <Orders> orders = new ArrayList<Orders>();

        try {
            
            for (Orders order : getOrders()){                
                for (Items items: order.getItemsList()){                    
                    if (items.getProdid()==productID){
                        orders.add(order);
                        break;
                    }
                }                
            }
            
        } catch (javax.persistence.NoResultException e) {
            throw e;
        }
        return orders;
    }
    
}
